package com.entrogy.AccessToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.Sinewecology.EntropyWechat.AccessToken;
import com.Sinewecology.EntropyWechat.WX_HttpsUtil;
import com.entrogy.bean.GongZhongHaoEntity;
import com.entrogy.bean.PubCountEntity;
import com.entrogy.dao.GongZhongHaoMapper;
import com.entrogy.dao.MessageMapper;
import com.entrogy.utils.RedisUtil;
import com.entrogy.utils.SendUtils;
import org.apache.http.ParseException;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * xlr
 */
@Component
public class WX_TokenUtil {

	private static Logger logger = LoggerFactory.getLogger(WX_TokenUtil.class);
	private static int count = 0;//计数器

	private static RedisUtil redisUtil = new RedisUtil();
	private static WX_TokenUtil wxTokenUtil;
	@Autowired
	private GongZhongHaoMapper gongZhongHaoMapper;
	@Autowired
	private MessageMapper messageMapper;


	@PostConstruct
	public void init(){
		wxTokenUtil = this;
		wxTokenUtil.gongZhongHaoMapper = this.gongZhongHaoMapper;
		wxTokenUtil.messageMapper = this.messageMapper;
	}

	/**
	 * 获得微信 AccessToken access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
	 * 开发者需要access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取 的access_token失效。
	 * （此处我是把token存在Redis里面了）
	 *
	 * @throws IOException
	 * @throws ParseException
	 */
	public static void getWXToken(GongZhongHaoEntity gongZhongHaoEntity) throws ParseException, IOException {
		count++;
		logger.info("发送取AccessToken的Get请求!");
		// TODO 支持多个公众号
		//获取多个公众号
		String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gongZhongHaoEntity.getAppid()
				+ "&secret=" + gongZhongHaoEntity.getAppsecret();
		JSONObject jsonObject = null;
		while (jsonObject == null) {
			jsonObject = WX_HttpsUtil.httpsRequest(tokenUrl, "GET", null);
			logger.info("jsonObject: " + jsonObject);
		}

		if (null != jsonObject) {
			try {
				String accessToken = jsonObject.getString("access_token");
				Integer expiresIn = jsonObject.getInteger("expires_in");
				//更新对应公众号的TOKEN及其过期时间信息
				wxTokenUtil.gongZhongHaoMapper.updateWxToken(gongZhongHaoEntity.getUsername(),accessToken,expiresIn);
				String usernameKey = gongZhongHaoEntity.getUsername();
				//存储WXTOKEN 失效时间为6900秒
				redisUtil.set(usernameKey, accessToken, expiresIn - 300);
				logger.info("获取access_token成功，有效时长{}秒 ==>" + AccessToken.getExpiresin());
			} catch (Exception e) {
				//获取token失败
				logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
				PubCountEntity pubCountEntity = wxTokenUtil.messageMapper.getPubCountOpenidByPhone("15379001543");
				// 通知管理员
				String[] paramsWeiXin = { "",  "系统", "系统", new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()), "获取WXTOKEN出问题啦啦啦==>errcode===="+jsonObject.getInteger("errcode")+"errmsg=="+jsonObject.getString("errmsg"), ""};
				SendUtils.sendByWeixin(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId());
				if(count < 3){//失败后获取三次之后跳走 不去轮训
					getWXToken(gongZhongHaoEntity);//重新获取token
				}
			}
		}
	}
}
